package com.kd.controller;

import com.kd.common.E_UserLoginToken;
import com.kd.common.PageResult;
import com.kd.common.Result;
import com.kd.entity.Employee;
import com.kd.enums.employee.EmployeeStatus;
import com.kd.enums.employee.PermissionLevel;
import com.kd.service.employee.EmployeeService;
import com.kd.service.token.EmployeeTokenService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;
    @Autowired
    EmployeeTokenService tokenService;


@RequestMapping("/login")
public Result<Employee> login(@RequestBody Employee loginmanager) {

    Employee storeEmployee = employeeService.findEmployeeByEId(loginmanager.getEid());
    if (storeEmployee == null) {
        return Result.fail(" 用户不存在");
    }
    // 调试3：手动验证密码
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    boolean isMatch = encoder.matches(loginmanager.getPassword(),  storeEmployee.getPassword());
    System.out.println(" 密码比对结果: " + isMatch);

    if (isMatch) {
        System.out.println("name"+storeEmployee.getName());
        String token = tokenService.getToken(storeEmployee);
        return Result.success(storeEmployee,  "登录成功", token);
    } else {
        return Result.fail(" 账号或密码错误");
    }
}


    @RequestMapping("/register")
    public Result.RegisterResult<Integer> register(@RequestBody Employee employee) {

        // 1. 参数基础校验
        if (employee.getCardid()  == null || employee.getCardid().trim().isEmpty())  {
            return Result.RegisterResult.fail(" 身份证号不能为空");
        }

        // 2. 查重验证
        Integer existMid = employeeService.getEidByCardid(employee.getCardid());
        if (existMid != null && existMid != 0) {
            return Result.RegisterResult.<Integer>fail("注册失败，已注册的工号：" + existMid)
                    .data(existMid);
        }

        // 3. 执行注册
        try {
            employee.setStatus(EmployeeStatus.ON_JOB.getCode());//默认在职
            if (employeeService.getEmployeeCount()==0) {//第一个为高管
                employee.setPermission(PermissionLevel.EXECUTIVE.getCode());
            }else{                                      //否则为普通
                employee.setPermission(PermissionLevel.NORMAL.getCode());
            }
            employee.setHiredate(new Date());
            boolean success = employeeService.insert(employee);
            if (success) {
                employee.setEid(employeeService.getEidByCardid(employee.getCardid()));
                return Result.RegisterResult.success(employee.getEid())
                        .message("注册成功"); // 使用链式调用设置消息
            }
            return Result.RegisterResult.fail(" 系统繁忙，注册失败");
        } catch (Exception e) {
            return Result.RegisterResult.fail(" 注册异常：" + e.getMessage());
        }
    }





    /**
     * 基于游标的通用过滤查询
     */
    @RequestMapping("/list/filters")
    @E_UserLoginToken
    public Result<PageResult<Employee,Integer>> getEmployeeListWithFilters(
            @RequestParam(required = false) Integer cursor,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) Integer eid,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Date hiredate,
            @RequestParam(required = false) Integer status, //0离职/1休假/2在职
            @RequestParam(required = false) Boolean hasImage,
            @RequestParam(required = false) Integer permission) { //0普通权限/1财务权限/2高层权限
        try {
            PageResult<Employee,Integer> pageResult = employeeService.findEmployeeListWithFilters(
                    cursor, limit, eid, name, hiredate, status, hasImage, permission
            );
            return Result.success(pageResult, "查询成功");
        } catch (Exception e) {
            return Result.fail(500, "查询失败: " + e.getMessage());
        }
    }



    @RequestMapping("/setPermission")
    @E_UserLoginToken
    public Result<Employee> setPermission(@RequestBody Map<String, Integer> params, HttpServletRequest request) {
        try {
            Integer eid = params.get("eid");
            Integer permission = params.get("permission");

            if (eid == null || permission == null) {
                return Result.fail(" 参数错误：eid和permission不能为空");
            }
            // 权限验证（只有高层可以设置权限）
            Employee currentUser = tokenService.getCurrentUser(request);
            if (currentUser == null || currentUser.getPermission()  < PermissionLevel.EXECUTIVE.getCode())  {
                return Result.fail(403,  "权限不足，只有高层管理人员可以设置权限");
            }
            Employee employee = employeeService.setPermission(eid,  permission);
            return Result.success(employee,  "权限设置成功");
        } catch (Exception e) {
            return Result.fail(500,  "权限设置失败: " + e.getMessage());
        }
    }






}
